<?php

/* 
 * @author myf
 * @date 2014-12-26
 * @description 编码相关
 */

namespace MyfApi\Libs;

class Coding
{
    private static $mapbit = array(
        5,  2,  4,  1,
        29,  3, 28,  0,
        13,  7, 11,  6,
        8, 12,  9, 10,

        15, 14, 23, 16,
        21, 25, 24, 18,
        20, 17, 27, 22,
        26, 19, 30, 31,
    );


    /**
     * 编码字符串
     *
     * @param string $str string
     *
     * @return string
     */
    public static function strEncode($str)
    {
        $len = strlen($str);
        if (!$len) {
            return;
        }
        $factor = mt_rand(1, min(255, ceil($len / 3)));
        $c = $factor % 10;

        $slice = str_split($str, $factor);
        for ($i=0; $i < count($slice); $i++) {
            for ($j=0; $j< strlen($slice[$i]); $j ++) {
                $slice[$i][$j] = chr(ord($slice[$i][$j]) + $c + $i);
            }
        }
        $ret = pack('C', $factor).implode('', $slice);
        return self::base64URLEncode($ret);
    }

    /**
     * 解码字符串
     *
     * @param string $str string
     *
     * @return string
     */
    public static function strDecode($str)
    {
        if ($str == '') {
            return;
        }
        $str = self::base64URLDecode($str);
        $factor = ord(substr($str, 0, 1));
        $c = $factor % 10;
        $entity = substr($str, 1);
        $slice = str_split($entity, $factor);
        if (!$slice) {
            return false;
        }
        for ($i=0; $i < count($slice); $i++) {
            for ($j =0; $j < strlen($slice[$i]); $j++) {
                $slice[$i][$j] = chr(ord($slice[$i][$j]) - $c - $i);
            }
        }
        return implode($slice);
    }


    /**
     * base64 url encode
     *
     * @param string $data string
     *
     * @return string
     */
    private static function base64URLEncode($data)
    {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }

    /**
     * base64 url decode
     *
     * @param string $data string
     *
     * @return string
     */
    private static function base64URLDecode($data)
    {
        return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
    }

}


